package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.WmThreadLocalUtil;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;

    @Autowired
    private WmMaterialMapper wmMaterialMapper;

    @Autowired
    private WmNewsAutoScanService autoScanService;

    @Autowired
    private WmNewsTaskService wmNewsTaskService;

    /**
     * 查询文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        //1. 校验参数
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        dto.checkParam();

        WmUser user = WmThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //2. 设置分页参数
        IPage<WmNews> page = new Page<>(dto.getPage(), dto.getSize());

        //3. 设置查询条件
        LambdaQueryWrapper<WmNews> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if(null != dto.getStatus()){
            lambdaQueryWrapper.eq(WmNews::getStatus, dto.getStatus());
        }

        if(null != dto.getChannelId()){
            lambdaQueryWrapper.eq(WmNews::getChannelId, dto.getChannelId());
        }

        if(StringUtils.isNotEmpty(dto.getKeyword())){
            lambdaQueryWrapper.like(WmNews::getTitle, dto.getKeyword());
        }

        if(null != dto.getBeginPubDate() && null != dto.getEndPubDate()){
            lambdaQueryWrapper.between(WmNews::getPublishTime, dto.getBeginPubDate(),dto.getEndPubDate());
        }
        //4. 查询数据
        page(page, lambdaQueryWrapper);

        //5. 封装返回结果
        PageResponseResult pageResponseResult = new PageResponseResult();
        pageResponseResult.setTotal((int) page.getTotal());
        pageResponseResult.setData(page.getRecords());

        pageResponseResult.setCurrentPage(dto.getPage());
        pageResponseResult.setSize(dto.getSize());

        return pageResponseResult;
    }

    /**
     * 发布文章或保存草稿
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult submitNews(WmNewsDto dto) throws Exception {
        //1. 校验参数
        if(null == dto){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        }

        WmUser user = WmThreadLocalUtil.getUser();
        if(null == user){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 保存或者更新文章内容
        WmNews wmNews = saveOrUpdateNews(dto,user);

        //2.1 如果是保存草稿则返回成功
        if(dto.getStatus().equals(WmNews.Status.NORMAL.getCode())){
            return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
        }

        //2.2 抽取内容中的所有的图片
        List<String> urls = ectractUrlInfo(dto.getContent());

        //3. 保存内容图片与素材之间的关系
        saveRelativeInfoForContent(urls, wmNews);

        //4. 保存封面图片与素材之间的关系
        saveRelativeInfoForCover(urls, wmNews,dto);

        /*//完成文章的自动审核操作
        autoScanService.autoScanWmNews(wmNews.getId());*/

        //添加任务到Schedule服务
        wmNewsTaskService.addWmNewsToTask(wmNews);

        //5. 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 保存封面图片和素材之间的关系
     * @param urls
     * @param wmNews
     * @param dto
     */
    private void saveRelativeInfoForCover(List<String> urls, WmNews wmNews, WmNewsDto dto) {
        //1. 获取传递过来的封面图片
        List<String> images = dto.getImages();

        //1.1 处理封面位自动的情况
        if(dto.getType() == -1){
            if(null == urls || urls.size() == 0){
                wmNews.setType((short)0);
            }else if(urls.size() < 3){
                wmNews.setType((short)1);

                images = urls.stream().limit(1).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(images.toArray(), ","));
            }else{
                wmNews.setType((short)3);
                images = urls.stream().limit(3).collect(Collectors.toList());
                wmNews.setImages(StringUtils.join(images.toArray(), ","));
            }

            //更新文章封面的类型
            updateById(wmNews);
        }

        //2. 判断封面是否是无图
        if(null != images && images.size() > 0){
            //保存关联关系
            saveRelativeInfo(images, wmNews, (byte) 1);
        }
    }

    /**
     * 保存文章内容图片和素材之间的关系
     * @param urls
     * @param wmNews
     */
    private void saveRelativeInfoForContent(List<String> urls, WmNews wmNews) {
        saveRelativeInfo(urls, wmNews, (byte) 0);
    }

    private void saveRelativeInfo(List<String> urls, WmNews wmNews, byte type){
        if(null == urls || urls.size() == 0){
            return;
        }
        //1. 对urls进行去重
        urls = urls.stream().distinct().collect(Collectors.toList());

        //2. 通过url地址查询素材的id
        List<WmMaterial> wmMaterials = wmMaterialMapper
                .selectList(Wrappers.<WmMaterial>lambdaQuery()
                        .in(WmMaterial::getUrl, urls));

        List<Integer> ids = wmMaterials.stream().map(item -> item.getId()).collect(Collectors.toList());

        //3. 判断素材是否有被删除过
        if(null == ids || ids.size() != urls.size()){
            throw new CustomException(AppHttpCodeEnum.MATERIAL_REFERENCE_FAIL);
        }

        //4. 批量保存文章和素材之间的关系
        wmNewsMaterialMapper.batchInsert(wmNews.getId(), ids, type);
    }

    /**
     * 抽取文章内容中的图片地址
     * @param content
     * @return
     */
    private List<String> ectractUrlInfo(String content) {
        List<String> urls = new ArrayList<>();
        List<Map> list = JSON.parseArray(content, Map.class);

        if(null != list && list.size() > 0){
            for (Map map : list) {
                if(map.get("type").equals("image")){
                    urls.add(map.get("value").toString());
                }
            }
        }

        return urls;
    }

    /**
     * 保存或者更新文章的数据
     * @param dto
     * @param wmUser
     */
    private WmNews saveOrUpdateNews(WmNewsDto dto, WmUser wmUser) {

        WmNews wmNews = new WmNews();
        BeanUtils.copyProperties(dto, wmNews);
        //处理图片
        String images = StringUtils.join(dto.getImages().toArray(), ",");

        wmNews.setImages(images);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        wmNews.setUserId(wmUser.getId());

        //处理自动-数据库使用了unsigned修饰不能存储负数
        if(dto.getType() == -1){
            wmNews.setType(null);
        }

        //文章的新增
        if(null == dto.getId()){
            save(wmNews);

        }else{
            //文章的修改
            //删除文章和素材之间的关系
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId, dto.getId()));

            updateById(wmNews);
        }

        return wmNews;
    }
}
